<template>
  <div style="margin-bottom: 10px">
    <span style="font-size: 25px;font-weight: bold;justify-content: center">以下是仓库药品信息</span>
  </div>

  <div>
    <div class="card" style="margin-bottom: 10px">
      <el-input placeholder="请输入药品名称进行查询" style="width: 200px" v-model="data.productName"></el-input>
      <el-button type="primary"  style="margin-left: 10px" @click="load()">查询</el-button>
      <el-button type="warning"  style="margin-left: 10px" @click="reset">重置</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px">
      <div style="margin-bottom: 10px">
        <el-button type="primary" plain @click="handleAdd">入库新药品</el-button>
        <el-button type="danger" plain @click="delBatch">删除药品</el-button>
      </div>
      <div class="table">
        <el-table :data="data.tableData" stripe max-height="450px" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" fixed="left"></el-table-column>
          <el-table-column prop="productName" label="药品名称" fixed="left"></el-table-column>
          <el-table-column label="药品图片" fixed="left">
            <template #default="scope">
              <el-image
                  :src="scope.row.imageUrl"
                  :preview-src-list="[scope.row.imageUrl]"
                  preview-teleported
                  style="width: 40px; height: 40px; border-radius: 50%"></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="药品价格"></el-table-column>
          <el-table-column prop="unit" label="价格和库存单位"></el-table-column>
          <el-table-column prop="stockQuantity" label="盘点的库存数量"/>
          <el-table-column prop="stockTakingUserName" label="盘点人姓名"></el-table-column>
          <el-table-column prop="currentStock" label="当前系统库存"></el-table-column>
          <el-table-column prop="description" label="药品描述" show-overflow-tooltip width="200"></el-table-column>
          <el-table-column prop="category" label="药品类别" show-overflow-tooltip width="200"></el-table-column>
          <el-table-column prop="stockTakingDate" label="盘点时间" width="170"></el-table-column>
          <el-table-column prop="uploadDate" label="药品入库时间" width="170"></el-table-column>
          <el-table-column label="操作" align="center" width="180" fixed="right">
            <template v-slot="scope">
              <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)">补货</el-button>
              <el-button size="mini" type="danger" plain @click="del(scope.row.sellerProductId)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
              style="margin-top: 5px"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="data.pageNum"
              :page-sizes="[3, 5, 10, 15, 20]"
              :page-size="data.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="data.total">
          </el-pagination>
        </div>
      </div>

    </div>
  </div>

  <el-dialog title="药品信息" v-model="data.formVisible" width="50%" :close-on-click-modal="false" destroy-on-close>
    <el-form :model="data.form" label-width="150px" style="padding-right: 50px" :rules="rules" ref="productForm">
      <el-form-item label="药品名称" prop="productName">
        <el-input v-model="data.form.productName" placeholder="药品名称"></el-input>
      </el-form-item>
      <el-form-item label="药品类别" prop="category">
        <el-input v-model="data.form.category" placeholder="药品类别"></el-input>
      </el-form-item>
      <el-form-item label="药品价格" prop="price">
        <el-input-number v-model="data.form.price" placeholder="药品价格"  :precision="2" :step="0.01" :min="0"></el-input-number> 元
      </el-form-item>
      <el-form-item label="价格单位" prop="unit">
        <el-input v-model="data.form.unit" placeholder="价格单位" ></el-input>
      </el-form-item>
      <el-form-item label="盘点药品库存数量" prop="stockQuantity">
        <el-input-number v-model="data.form.stockQuantity" placeholder="盘点库存数量" :min="0"></el-input-number>{{data.form.unit}}
      </el-form-item>
      <el-form-item label="当前库存" prop="currentStock">
        <el-input-number v-model="data.form.currentStock" placeholder="当前系统库存数量" :min="0"  ></el-input-number>{{data.form.unit}}
      </el-form-item>

    <el-form-item prop="inventoryRecommand" label="库存保有量建议" v-if="data.operation !=='add'">
        <el-alert
            :title="data.title"
            type="warning"
            description="网络构建中..."
            :closable="false"
            style="margin-bottom: 10px;">
          <template #default>
            <p style="font-weight: bold; color: red; margin-left: 100px;font-size: 20px">最佳库存量：{{data.form.inventoryRecommand}}{{data.form.unit}}</p>
          </template>
        </el-alert>
      </el-form-item>


      <el-form-item label="药品描述" prop="description">
        <el-input type="textarea" v-model="data.form.description" placeholder="药品描述"></el-input>
      </el-form-item>

      <el-form-item label="药品图片" prop="imageUrl">
        <el-upload :action="uploadUrl" list-type="picture" :on-success="handleImgSuccess">
          <el-button type="primary">上传图片</el-button>
        </el-upload>
      </el-form-item>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="data.formVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">保 存</el-button>
      </span>
    </template>
  </el-dialog>

</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'

import {
  deleteBatchSellerProductApi,
  deleteSellerProductApi, loadInventoryRecommendation,
  loadSellerProductApi,
  saveSellerProductApi
} from "@/utils/API/shop/SellerProduct";
const uploadUrl = import.meta.env.VITE_BASE_URL + '/files/upload'
// 定义响应式数据
const data = reactive({
  tableData: [],  // 表格数据
  pageNum: 1,     // 当前页码
  pageSize: 10,   // 每页显示数量
  total: 0,       // 总记录数
  name: null,     // 搜索条件
  formVisible: false, // 表单显示状态
  form: {},       // 表单数据
  ids: [],        // 选中数据的ID
  productName: null,
  user: JSON.parse(localStorage.getItem('system-user') || '{}'),
  operation:'',
  title:'根据销售订单、退货订单以及货物报损各数据进行分析，为您推荐的最佳库存保有量为',
  quantity:0,
})


const load = () => {
  let params = {
    pageNum: data.pageNum,
    pageSize: data.pageSize,
    productName: data.productName,
  }
  loadSellerProductApi(params).then(res => {
    if (res.code === '200') {
      data.tableData = res.data?.list
      data.total = res.data?.total
    } else {
      ElMessage.error(res.msg)
    }
  })
}
load()

const handleEdit = (row) => {
  loadInventoryRecommendation(row.sellerProductId).then(res => {
    console.log(res)
    data.form.inventoryRecommand = res.data
    if(data.form.inventoryRecommand < 5){
      data.title = '以下是我们根据销售订单、退货订单以及货物报损各数据进行分析，为您推荐的最佳库存保有量。当前商品销售订单较少或退货数量较多，请考虑是否将商品下架，并从库存管理中删除该商品。'
    }
  })
   data.quantity = row.stockQuantity
  data.form = JSON.parse(JSON.stringify(row))

  data.formVisible = true
  data.operation ='edit'
}

const del = (id) => {
  ElMessageBox.confirm('您确定删除吗？', '确认删除', { type: 'warning' }).then(() => {
    deleteSellerProductApi(id).then(res => {
      if (res.code === '200') {
        ElMessage.success('出库成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(() => {})
}


// 批量出库
const delBatch = () => {
  if (!data.ids.length) {
    ElMessage.warning('请选择数据')
    return
  }
  ElMessageBox.confirm('您确定批量删除这些数据吗？', '确认删除', { type: 'warning' }).then(() => {
    deleteBatchSellerProductApi(data.ids).then(res => {
      if (res.code === '200') {
        ElMessage.success('出库成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(() => {})
}


// 重置筛选条件
const reset = () => {
  data.productName = null
  load()
}

// 处理页码变化
const handleCurrentChange = (pageNum) => {
  data.pageNum = pageNum
  load()
}
const handleSizeChange=(pageSize)=> {
  data.pageSize = pageSize
  load()
}
// 处理选中的行
const handleSelectionChange = (rows) => {
  data.ids = rows.map(v => v.sellerProductId)
}

// 入库数据
const handleAdd = () => {
  data.form = {}
  data.operation = 'add'
  data.formVisible = true

}

const productForm = ref()
// 校验规则
const rules = {
  productName: [
    { required: true, message: '请输入药品名称', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入药品价格', trigger: 'blur' },
  ],
  stockQuantity: [
    { required: true, message: '请输入药品库存', trigger: 'blur' },
  ],
  description: [
    { required: true, message: '请输入药品描述', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请输入药品类别', trigger: 'blur' }
  ],
  currentStock : [
    { required: true, message: '请输入当前库存', trigger: 'blur' }
  ]

}
const handleImgSuccess = (res) => {
  data.form.imageUrl = res.data  // res.data就是文件上传返回的文件路径，获取到路径后赋值表单的属性
}

// 提交表单
const submitForm = () => {
  productForm.value.validate((valid) => {
    if (valid) {
      save()
    } else {
      ElMessage.error('请填写必须的参数！');
      return false;
    }
  });
}

const save = () => {
  if(data.form.stockQuantity !== data.quantity  ){
    data.form.stockTakingUserName = data.user.name
  }
    let resp = saveSellerProductApi(data.form)//调用接口
    resp.then(res => {
      if (res.code === '200') {
        ElMessage.success('药品库更新成功')
        data.formVisible = false
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })

}

</script>

<style scoped>
@import '@/assets/css/tabelContent.css';
</style>